package com.zdkj.subway.check.controller.subwayRat.TVMRevenueVarianceAudit.TvmChaYiDXC;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.controller.CommonController;
import com.zdkj.subway.check.dto.SwAuTvmCashAndItvmAmountHierarchyDifferenceDto;
import com.zdkj.subway.check.entity.*;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.SwAuItvmOnlineAmountHierarchyDifferenceMapper;
import com.zdkj.subway.check.mapper.SwAuTvmCashAmountHierarchyDifferenceMapper;
import com.zdkj.subway.check.mapper.SwParamLineMapper;
import com.zdkj.subway.check.mapper.SwParamStationMapper;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.service.SwAuItvmOnlineAmountHierarchyDifferenceService;
import com.zdkj.subway.check.service.SwAuTvmCashAmountHierarchyDifferenceServices;
import com.zdkj.subway.check.util.DateFormat;
import com.zdkj.subway.check.util.LocalDateConverter;
import com.zdkj.subway.check.util.LocalDateTimeConverter;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;

/**
 *
 */
@Slf4j
@RestController
@RequestMapping("/checkNew")
public class SwAuTvmCashAmountHierarchyDifferenceCtrl {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwAuTvmCashAmountHierarchyDifference.class);
    @Resource
    private SwAuTvmCashAmountHierarchyDifferenceMapper swAuTvmCashAmountHierarchyDifferenceMapper;
    @Resource
    private SwAuItvmOnlineAmountHierarchyDifferenceMapper swAuItvmOnlineAmountHierarchyDifferenceMapper;
    @Autowired
    private CommonController commonController;
    @Autowired
    private SwParamLineMapper swParamLineMapper;
    @Autowired
    private SwParamStationMapper swParamStationMapper;
    @Autowired
    private SwAuTvmCashAmountHierarchyDifferenceServices swAuTvmCashAmountHierarchyDifferenceServices;
    @Autowired
    private SwAuItvmOnlineAmountHierarchyDifferenceService swAuItvmOnlineAmountHierarchyDifferenceService;


    /**
     * 导出
     * @param
     * @return
     */
    @ApiOperation(value = "TVM层级差异导出", notes = "TVM层级差异导出")
    @GetMapping({"/exportTvmCashAmountHierarchy"})
    @SysLog("TVM层级差异导出")
    public void export(String ids, String tag, SwAuTvmCashAmountHierarchyDifference params, HttpServletResponse response) throws ParseException {
        swAuTvmCashAmountHierarchyDifferenceServices.export(ids,tag,params,response);
    }

    /**
     * 批量回馈差异原因
     * @param jsonObject
     * @return
     */
    @RequestMapping("/updateSwAuTvmCashAmountHierarchyDifferenceToHKBF")
    @ApiOperation(value = "批量回馈差异原因", notes = "批量回馈差异原因")
    public Result updateSwAuTvmCashAmountHierarchyDifferenceToHKBF(@RequestBody JSONObject jsonObject){
        List<Map<String,Object>> list = (List)jsonObject.getJSONArray("list");
        for(Map<String,Object> m : list){
            String payType = String.valueOf(m.get("payType"));
            //根据支付方式
            if("1".equals(payType)){
                SwAuTvmCashAmountHierarchyDifference swAuTvmCashAmountHierarchyDifference = new SwAuTvmCashAmountHierarchyDifference();
                swAuTvmCashAmountHierarchyDifference.setId(Integer.valueOf(String.valueOf(m.get("id"))));
                swAuTvmCashAmountHierarchyDifference.setQfReplyReason(jsonObject.getString("qfReplyReason"));
                swAuTvmCashAmountHierarchyDifference.setQfReplyDetail(jsonObject.getString("qfReplyDetail"));
                swAuTvmCashAmountHierarchyDifferenceMapper.updateById(swAuTvmCashAmountHierarchyDifference);
            }else{
                SwAuItvmOnlineAmountHierarchyDifference swAuItvmOnlineAmountHierarchyDifference = new SwAuItvmOnlineAmountHierarchyDifference();
                swAuItvmOnlineAmountHierarchyDifference.setId(Integer.valueOf(String.valueOf(m.get("id"))));
                swAuItvmOnlineAmountHierarchyDifference.setQfReplyReason(jsonObject.getString("qfReplyReason"));
                swAuItvmOnlineAmountHierarchyDifference.setQfReplyDetail(jsonObject.getString("qfReplyDetail"));
                swAuItvmOnlineAmountHierarchyDifferenceMapper.updateById(swAuItvmOnlineAmountHierarchyDifference);
            }
        }
        return new Result(ResultDetailMsg.OK);
    }

    /**
     * 回馈预览
     * @param jsonObject
     * @return
     */
    @RequestMapping("/updateSwAuTvmCashAmountHierarchyDifferenceToHK")
    @ApiOperation(value = "回馈预览", notes = "回馈预览")
    public Result updateSwAuTvmCashAmountHierarchyDifferenceToHK(@RequestBody JSONObject jsonObject){
        Integer id = jsonObject.getInteger("id");
        String payType = jsonObject.getString("payType");
        //支付方式判断
        if("1".equals(payType)){
            SwAuTvmCashAmountHierarchyDifference swAuTvmCashAmountHierarchyDifference = new SwAuTvmCashAmountHierarchyDifference();
            swAuTvmCashAmountHierarchyDifference.setId(id);
            swAuTvmCashAmountHierarchyDifference.setQfReplyDetail(jsonObject.getString("qfReplyDetail"));
            swAuTvmCashAmountHierarchyDifference.setQfReplyReason(jsonObject.getString("qfReplyReason"));
            swAuTvmCashAmountHierarchyDifference.setReplySaleMoney(jsonObject.getBigDecimal("replySaleMoney"));
            swAuTvmCashAmountHierarchyDifference.setReplyRechargeMoney(jsonObject.getBigDecimal("replyRechargeMoney"));
            swAuTvmCashAmountHierarchyDifference.setReplyErrorReturnMoney(jsonObject.getBigDecimal("replyErrorReturnMoney"));
            swAuTvmCashAmountHierarchyDifference.setReplyComparativeSaleMoney(jsonObject.getBigDecimal("replyComparativeSaleMoney"));
            swAuTvmCashAmountHierarchyDifference.setReplyComparativeRechargeMoney(jsonObject.getBigDecimal("replyComparativeRechargeMoney"));
            swAuTvmCashAmountHierarchyDifference.setReplyComparativeErrorReturnMoney(jsonObject.getBigDecimal("replyComparativeErrorReturnMoney"));
            swAuTvmCashAmountHierarchyDifferenceMapper.updateById(swAuTvmCashAmountHierarchyDifference);
        }else{
            SwAuItvmOnlineAmountHierarchyDifference swAuItvmOnlineAmountHierarchyDifference = new SwAuItvmOnlineAmountHierarchyDifference();
            swAuItvmOnlineAmountHierarchyDifference.setId(id);
            swAuItvmOnlineAmountHierarchyDifference.setQfReplyDetail(jsonObject.getString("qfReplyDetail"));
            swAuItvmOnlineAmountHierarchyDifference.setQfReplyReason(jsonObject.getString("qfReplyReason"));
            swAuItvmOnlineAmountHierarchyDifference.setReplySaleMoney(jsonObject.getBigDecimal("replySaleMoney"));
            swAuItvmOnlineAmountHierarchyDifference.setReplyRechargeMoney(jsonObject.getBigDecimal("replyRechargeMoney"));
            swAuItvmOnlineAmountHierarchyDifference.setReplyErrorReturnMoney(jsonObject.getBigDecimal("replyErrorReturnMoney"));
            swAuItvmOnlineAmountHierarchyDifference.setReplyComparativeSaleMoney(jsonObject.getBigDecimal("replyComparativeSaleMoney"));
            swAuItvmOnlineAmountHierarchyDifference.setReplyComparativeRechargeMoney(jsonObject.getBigDecimal("replyComparativeRechargeMoney"));
            swAuItvmOnlineAmountHierarchyDifference.setReplyComparativeErrorReturnMoney(jsonObject.getBigDecimal("replyComparativeErrorReturnMoney"));
            swAuItvmOnlineAmountHierarchyDifferenceMapper.updateById(swAuItvmOnlineAmountHierarchyDifference);
        }
        return new Result(ResultDetailMsg.OK);
    }

    /**
     * 回馈数据
     * @param jsonObject
     * @return
     */
    @RequestMapping("/updateSwAuTvmCashAmountHierarchyDifference")
    @ApiOperation(value = "回馈数据", notes = "回馈数据")
    @Transactional(rollbackFor = Exception.class)
    public Result updateSwAuTvmCashboxAmountHierarchyDifference(@RequestBody JSONObject jsonObject){
        Result res=new Result(ResultDetailMsg.OK);
        try{
            List<Map<String,Object>> list = (List)jsonObject.getJSONArray("list");
            for(Map<String,Object> m : list){
                String payType = String.valueOf(m.get("payType"));
                if("1".equals(payType)){
                    SwAuTvmCashAmountHierarchyDifference swAuTvmCashAmountHierarchyDifference = new SwAuTvmCashAmountHierarchyDifference();
                    swAuTvmCashAmountHierarchyDifference.setId(Integer.valueOf(String.valueOf(m.get("id"))));
                    swAuTvmCashAmountHierarchyDifference.setQfReplyStatus("1");
                    swAuTvmCashAmountHierarchyDifference.setAssistStatus("3");
                    swAuTvmCashAmountHierarchyDifferenceMapper.updateById(swAuTvmCashAmountHierarchyDifference);
                }else{
                    SwAuItvmOnlineAmountHierarchyDifference swAuItvmOnlineAmountHierarchyDifference = new SwAuItvmOnlineAmountHierarchyDifference();
                    swAuItvmOnlineAmountHierarchyDifference.setId(Integer.valueOf(String.valueOf(m.get("id"))));
                    swAuItvmOnlineAmountHierarchyDifference.setQfReplyStatus("1");
                    swAuItvmOnlineAmountHierarchyDifference.setAssistStatus("3");
                    swAuItvmOnlineAmountHierarchyDifferenceMapper.updateById(swAuItvmOnlineAmountHierarchyDifference);
                }
            }
            Map param = JSONObject.parseObject(jsonObject.toString(),Map.class);
            //下发代办
            commonController.innerBatch(param);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("回馈失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return res;
    }

    /**
     * TVM层级差异-机电专业登录查看(SC) 列表
     * @param param
     * @return
     */
    @RequestMapping("/get_xw_SwAuTvmCashAmountHierarchyDifferenceList")
    @ApiOperation(value = "TVM层级差异-机电专业登录查看(SC) 列表", notes = "TVM层级差异-机电专业登录查看(SC) 列表")
    public Page get_xw_SwAuTvmCashAmountHierarchyDifferenceList(Page page, @RequestParam Map<String,String> param){
        param.put("assistStatusList","2,3");
        List<Map<String, Object>> swAuTvmCashAmountHierarchyDifferenceList = swAuTvmCashAmountHierarchyDifferenceMapper.get_xw_SwAuTvmCashAmountHierarchyDifferenceList(param);
        page.setData(swAuTvmCashAmountHierarchyDifferenceList,true);
        return page;
    }
    /**
     * TVM层级差异-机电登录查看(SC) 机电列表
     * @param swAuTvmCashAmountHierarchyDifference
     * @return
     */
//    @RequestMapping("get_xw_SwAuTvmCashAmountHierarchyDifferenceList")
//    public Result get_xw_SwAuTvmCashAmountHierarchyDifferenceList(@RequestBody SwAuTvmCashAmountHierarchyDifference swAuTvmCashAmountHierarchyDifference){
//        swAuTvmCashAmountHierarchyDifference.setLineCode(SecurityUtils.getUser().getLineCode());
//        swAuTvmCashAmountHierarchyDifference.setAssistStatus("1");
//        List<Map<String, Object>> swAuTvmCashAmountHierarchyList = swAuTvmCashAmountHierarchyDifferenceMapper.getTvmCashAmountHierarchyList(swAuTvmCashAmountHierarchyDifference);
//        JSONObject resultJson = new JSONObject();
//        resultJson.put("list", swAuTvmCashAmountHierarchyList);
//        PageInfo<SwAuTvmCashAmountHierarchyDifference> swAuTvmCashAmountHierarchyPageInfo = new PageInfo(swAuTvmCashAmountHierarchyList);
//        resultJson.put("pageInfo", swAuTvmCashAmountHierarchyPageInfo);
//        return new Result(ResultDetailMsg.OK, resultJson);
//    }

    /**
     * TVM层级差异-客运登录查看(SC) 客运列表
     * @param swAuTvmCashAmountHierarchyDifference
     * @return
     */
    @RequestMapping("/get_xw_SwAuTvmCashAmountHierarchyDifferenceListKY")
    @ApiOperation(value = "TVM层级差异-客运登录查看(SC) 客运列表", notes = "TVM层级差异-客运登录查看(SC) 客运列表")
    public Result get_xw_SwAuTvmCashAmountHierarchyDifferenceListKY(@RequestBody SwAuTvmCashAmountHierarchyDifference swAuTvmCashAmountHierarchyDifference){
        swAuTvmCashAmountHierarchyDifference.setLineCode(SecurityUtils.getUser().getLineCode());
        swAuTvmCashAmountHierarchyDifference.setStationCode(SecurityUtils.getUser().getStationCode());
        //协查状态
        swAuTvmCashAmountHierarchyDifference.setAssistStatus("1");
        List<Map<String, Object>> swAuTvmCashAmountHierarchyList = swAuTvmCashAmountHierarchyDifferenceMapper.getTvmCashAmountHierarchyList(swAuTvmCashAmountHierarchyDifference);
        JSONObject resultJson = new JSONObject();
        resultJson.put("list", swAuTvmCashAmountHierarchyList);
        PageInfo<SwAuTvmCashAmountHierarchyDifference> swAuTvmCashAmountHierarchyPageInfo = new PageInfo(swAuTvmCashAmountHierarchyList);
        resultJson.put("pageInfo", swAuTvmCashAmountHierarchyPageInfo);
        return new Result(ResultDetailMsg.OK, resultJson);
    }


    /**
     * TVM层级差异-其他运营中心登录查看(SC) 其他运营中心列表
     * @param swAuTvmCashAmountHierarchyDifference
     * @return
     */
    @RequestMapping("/get_xw_SwAuTvmCashAmountHierarchyDifferenceListOther")
    @ApiOperation(value = "TVM层级差异-其他运营中心登录查看(SC) 其他运营中心列表", notes = "TVM层级差异-其他运营中心登录查看(SC) 其他运营中心列表")
    public Result get_xw_SwAuTvmCashAmountHierarchyDifferenceListOther(@RequestBody SwAuTvmCashAmountHierarchyDifference swAuTvmCashAmountHierarchyDifference){
        swAuTvmCashAmountHierarchyDifference.setAssistStatus("1");
        List<Map<String, Object>> swAuTvmCashAmountHierarchyList = swAuTvmCashAmountHierarchyDifferenceMapper.getTvmCashAmountHierarchyList(swAuTvmCashAmountHierarchyDifference);
        JSONObject resultJson = new JSONObject();
        resultJson.put("list", swAuTvmCashAmountHierarchyList);
        PageInfo<SwAuTvmCashAmountHierarchyDifference> swAuTvmCashAmountHierarchyPageInfo = new PageInfo(swAuTvmCashAmountHierarchyList);
        resultJson.put("pageInfo", swAuTvmCashAmountHierarchyPageInfo);
        return new Result(ResultDetailMsg.OK, resultJson);
    }



    /**
     * TVM层级差异-机电专业登录查看(SC) -批量回馈差异原因
     * @param jsonObject
     * @return
     */
    @RequestMapping("/replaySwAuTvmCashAmountHierarchyDifferenceList")
    @ApiOperation(value = "TVM层级差异-机电专业登录查看(SC) -批量回馈差异原因", notes = "TVM层级差异-机电专业登录查看(SC) -批量回馈差异原因")
    public Result replaySwAuTvmCashAmountHierarchyDifferenceList(@RequestBody JSONObject jsonObject){
        Result res=new Result(ResultDetailMsg.OK);
        List<Map<String,Object>> list = (List)jsonObject.getJSONArray("list");
        for(Map<String,Object> m : list){
            String payType = String.valueOf(m.get("payType"));
            //支付类型 1现金 2电子
            if("1".equals(payType)){
                SwAuTvmCashAmountHierarchyDifference swAuTvmCashAmountHierarchyDifference = new SwAuTvmCashAmountHierarchyDifference();
                swAuTvmCashAmountHierarchyDifference.setId(Integer.valueOf(String.valueOf(m.get("id"))));
                swAuTvmCashAmountHierarchyDifference.setJdReplyReason(jsonObject.getString("jdReplyReason"));
                swAuTvmCashAmountHierarchyDifference.setJdReplyDetail(jsonObject.getString("jdReplyDetail"));
                swAuTvmCashAmountHierarchyDifferenceMapper.updateById(swAuTvmCashAmountHierarchyDifference);
            }else{
                SwAuItvmOnlineAmountHierarchyDifference swAuItvmOnlineAmountHierarchyDifference = new SwAuItvmOnlineAmountHierarchyDifference();
                swAuItvmOnlineAmountHierarchyDifference.setId(Integer.valueOf(String.valueOf(m.get("id"))));
                swAuItvmOnlineAmountHierarchyDifference.setJdReplyReason(jsonObject.getString("jdReplyReason"));
                swAuItvmOnlineAmountHierarchyDifference.setJdReplyDetail(jsonObject.getString("jdReplyDetail"));
                swAuItvmOnlineAmountHierarchyDifferenceMapper.updateById(swAuItvmOnlineAmountHierarchyDifference);
            }
        }
        return res;
    }

    /**
     * TVM层级差异-机电专业登录查看(SC) -单条回馈差异原因
     * @param jsonObject
     * @return
     */
    @RequestMapping("/replaySwAuTvmCashAmountHierarchyDifference")
    @ApiOperation(value = "TVM层级差异-机电专业登录查看(SC) -单条回馈差异原因", notes = "TVM层级差异-机电专业登录查看(SC) -单条回馈差异原因")
    public Result replaySwAuTvmCashAmountHierarchyDifference(@RequestBody JSONObject jsonObject){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            //支付类型 1现金 2电子
            String payType = jsonObject.getString("payType");
            if("1".equals(payType)){
                SwAuTvmCashAmountHierarchyDifference swAuTvmCashAmountHierarchyDifference = JSON.parseObject(jsonObject.toJSONString(),SwAuTvmCashAmountHierarchyDifference.class);
                swAuTvmCashAmountHierarchyDifference.setJdReplyTime(new Date());
                swAuTvmCashAmountHierarchyDifferenceMapper.updateById(swAuTvmCashAmountHierarchyDifference);
            }else{
                SwAuItvmOnlineAmountHierarchyDifference swAuItvmOnlineAmountHierarchyDifference = JSON.parseObject(jsonObject.toJSONString(),SwAuItvmOnlineAmountHierarchyDifference.class);
                swAuItvmOnlineAmountHierarchyDifference.setJdReplyTime(new Date());
                swAuItvmOnlineAmountHierarchyDifferenceMapper.updateById(swAuItvmOnlineAmountHierarchyDifference);
            }
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("回馈失败！");
        }
        return res;
    }

    /**
     * TVM层级差异-机电专业登录查看(SC) -提交
     * @param jsonObject
     * @return
     */
    @RequestMapping("/submitSwAuTvmCashAmountHierarchyDifference")
    @ApiOperation(value = "TVM层级差异-机电专业登录查看(SC) -提交", notes = "TVM层级差异-机电专业登录查看(SC) -提交")
    @Transactional(rollbackFor = Exception.class)
    public Result submitSwAuTvmCashAmountHierarchyDifference(@RequestBody JSONObject jsonObject){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            JSONArray ids = jsonObject.getJSONArray("ids");
            Map param = JSONObject.parseObject(jsonObject.toString(),Map.class);
            for(Object idObj:ids){
                SwAuTvmCashAmountHierarchyDifference swAuTvmCashAmountHierarchyDifference=new SwAuTvmCashAmountHierarchyDifference();
                swAuTvmCashAmountHierarchyDifference.setJdReplyTime(new Date());
                swAuTvmCashAmountHierarchyDifference.setAssistStatus("3");
                swAuTvmCashAmountHierarchyDifference.setId(Integer.valueOf(idObj.toString()));
                swAuTvmCashAmountHierarchyDifference.setJdReplyTime(new Date());
                swAuTvmCashAmountHierarchyDifferenceMapper.updateById(swAuTvmCashAmountHierarchyDifference);
            }
            commonController.innerBatch(param);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("回馈失败！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return res;
    }

    /**
     * 导出
     * @param
     * @return
     */
    @ApiOperation(value = "导出", notes = "导出")
    @GetMapping({"/exportTVMQF"})
    @SysLog("导出")
    public void export(String ids, String payTypes, SwAuTvmCashAndItvmAmountHierarchyDifferenceDto params, HttpServletResponse response) throws ParseException {
        //线路、站点、支付方式中文名 根据未回馈的查询 差异类型 compare_type = 4 and assist_status =2
        List<SwAuTvmCashAndItvmAmountHierarchyDifferenceDto> records = new ArrayList<>();
        if(ids == null || ids.isEmpty()) {
            Map<String,String> param = new HashMap<>();
            param.put("assistStatus","2");
            param.put("qfReplyStatus","0");
            param.put("compareType","4");
            if(StringUtils.isNotEmpty(params.getLineCode())){
                param.put("lineCode",params.getLineCode());
            }
            if(StringUtils.isNotEmpty(params.getStationCode())){
                param.put("stationCode",params.getStationCode());
            }
            if(StringUtils.isNotEmpty(params.getTvmOrder())){
                param.put("tvmOrder",params.getTvmOrder());
            }
            if(params.getSettleTime()!=null){
                param.put("settleTime", DateFormat.LocalDateTurnString(params.getSettleTime()));
            }
            if(StringUtils.isNotEmpty(params.getPayType())){
                param.put("payType",params.getPayType());
            }
            if(StringUtils.isNotEmpty(params.getQfReplyStatus())){
                param.put("qfReplyStatus",params.getQfReplyStatus());
            }
            List<Map<String, Object>> swAuTvmCashAmountHierarchyDifferenceList = swAuTvmCashAmountHierarchyDifferenceMapper.get_xw_SwAuTvmCashAmountHierarchyDifferenceList(param);
            //数据组织
            records = getMapList(swAuTvmCashAmountHierarchyDifferenceList);
//            if(CollectionUtil.isEmpty(records)){
//                throw new RuntimeException("请检查需要导出的数据是否符合规范!");
//            }
        }else {
            List<String> idCashLists = new ArrayList<>();//现金
            List<String> idEleLists = new ArrayList<>();//电子
            String[] payIds = payTypes.split(",");
            String[] idParam = ids.split(",");
            for (int i = 0; i < idParam.length; i++) {
                 String id = idParam[i];
                 String payType = payIds[i];
                if("1".equals(payType)){
                    idCashLists.add(id);
                }else {
                    idEleLists.add(id);
                }
            }
            List<SwAuTvmCashAmountHierarchyDifference> swAuTvmCashAmountHierarchyDifferences = null;
            List<SwAuItvmOnlineAmountHierarchyDifference> swAuItvmOnlineAmountHierarchyDifferences = null;
            if(CollectionUtils.isNotEmpty(idCashLists)){
                swAuTvmCashAmountHierarchyDifferences = swAuTvmCashAmountHierarchyDifferenceMapper.selectBatchIds(idCashLists);
            }
            if(CollectionUtils.isNotEmpty(idEleLists)){
                swAuItvmOnlineAmountHierarchyDifferences = swAuItvmOnlineAmountHierarchyDifferenceMapper.selectBatchIds(idEleLists);
            }
            //组织数据
            records = getList(swAuTvmCashAmountHierarchyDifferences,swAuItvmOnlineAmountHierarchyDifferences);
        }
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("TVM票款层级差异协查", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/export/SwAuTvmLcAndAccAssistExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("TVM票款层级差异协查").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("TVM票款层级差异协查导出失败");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }

    /**
     * 组织数据
     * @param swAuTvmCashAmountHierarchyDifferences
     * @param swAuItvmOnlineAmountHierarchyDifferences
     * @return
     */
    private List<SwAuTvmCashAndItvmAmountHierarchyDifferenceDto> getList(List<SwAuTvmCashAmountHierarchyDifference> swAuTvmCashAmountHierarchyDifferences, List<SwAuItvmOnlineAmountHierarchyDifference> swAuItvmOnlineAmountHierarchyDifferences) {
        List<SwAuTvmCashAndItvmAmountHierarchyDifferenceDto> records = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(swAuTvmCashAmountHierarchyDifferences)){

            swAuTvmCashAmountHierarchyDifferences.stream().forEach(x -> {
                SwAuTvmCashAndItvmAmountHierarchyDifferenceDto swAuTvmCashAndItvmAmountHierarchyDifferenceDto = new SwAuTvmCashAndItvmAmountHierarchyDifferenceDto();
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setId(x.getId());

                //线路
                SwParamLine swParamLine = swParamLineMapper.selectOne(Wrappers.<SwParamLine>lambdaQuery().eq(SwParamLine::getCode, x.getLineCode()));
                //站点
                SwParamStation swParamStation = swParamStationMapper.selectOne(Wrappers.<SwParamStation>lambdaQuery()
                        .eq(SwParamStation::getLineCode,x.getLineCode()).eq(SwParamStation::getCode, x.getStationCode()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setLineCode(swParamLine.getName());
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setStationCode(swParamStation.getName());
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setTvmCode(x.getTvmOrder());
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setSettleTime(DateFormat.dateTOLocalDate(x.getSettleTime()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setPayType("现金");
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setDepositAmount(getFixed(x.getDepositAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setSaleAmount(getFixed(x.getSaleAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setErrorRefundAmount(getFixed(x.getErrorRefundAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyRechargeMoney(getFixed(x.getReplyRechargeMoney()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplySaleMoney(getFixed(x.getReplySaleMoney()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyErrorReturnMoney(getFixed(x.getReplyErrorReturnMoney()));


                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setBeDepositAmount(getFixed(x.getBeDepositAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setBeSaleAmount(getFixed(x.getBeSaleAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setBeErrorRefundAmount(getFixed(x.getBeErrorRefundAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyComparativeRechargeMoney(getFixed(x.getReplyComparativeRechargeMoney()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyComparativeSaleMoney(getFixed(x.getReplyComparativeSaleMoney()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyComparativeErrorReturnMoney(getFixed(x.getReplyComparativeErrorReturnMoney()));

                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setQfReplyReason(StringUtils.isEmpty(x.getQfReplyReason()) ? " " : (x.getQfReplyReason().equals("1") ? "系统原因" : "非系统原因"));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setQfReplyDetail(StringUtils.isEmpty(x.getQfReplyDetail()) ? " " : x.getQfReplyDetail());
                records.add(swAuTvmCashAndItvmAmountHierarchyDifferenceDto);
            });
        }
        if(CollectionUtils.isNotEmpty(swAuItvmOnlineAmountHierarchyDifferences)){
            swAuItvmOnlineAmountHierarchyDifferences.stream().forEach(x -> {
                SwAuTvmCashAndItvmAmountHierarchyDifferenceDto swAuTvmCashAndItvmAmountHierarchyDifferenceDto = new SwAuTvmCashAndItvmAmountHierarchyDifferenceDto();
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setId(x.getId());

                SwParamLine swParamLine = swParamLineMapper.selectOne(Wrappers.<SwParamLine>lambdaQuery().eq(SwParamLine::getCode, x.getLineCode()));
                SwParamStation swParamStation = swParamStationMapper.selectOne(Wrappers.<SwParamStation>lambdaQuery()
                        .eq(SwParamStation::getLineCode,x.getLineCode()).eq(SwParamStation::getCode, x.getStationCode()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setLineCode(swParamLine.getName());
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setStationCode(swParamStation.getName());
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setTvmCode(x.getTvmOrder());
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setSettleTime(DateFormat.dateTOLocalDate(x.getSettleTime()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setPayType("电子");
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setDepositAmount(getFixed(x.getDepositAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setSaleAmount(getFixed(x.getSaleAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setErrorRefundAmount(getFixed(x.getErrorRefundAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyRechargeMoney(getFixed(x.getReplyRechargeMoney()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplySaleMoney(getFixed(x.getReplySaleMoney()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyErrorReturnMoney(getFixed(x.getReplyErrorReturnMoney()));

                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setBeDepositAmount(getFixed(x.getBeDepositAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setBeSaleAmount(getFixed(x.getBeSaleAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setBeErrorRefundAmount(getFixed(x.getBeErrorRefundAmount()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyComparativeRechargeMoney(getFixed(x.getReplyComparativeRechargeMoney()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyComparativeSaleMoney(getFixed(x.getReplyComparativeSaleMoney()));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyComparativeErrorReturnMoney(getFixed(x.getReplyComparativeErrorReturnMoney()));

                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setQfReplyReason(StringUtils.isEmpty(x.getQfReplyReason()) ? " " : (x.getQfReplyReason().equals("1") ? "系统原因" : "非系统原因"));
                swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setQfReplyDetail(StringUtils.isEmpty(x.getQfReplyDetail()) ? " " : x.getQfReplyDetail());
                records.add(swAuTvmCashAndItvmAmountHierarchyDifferenceDto);
            });
        }
        return records;
    }


    /**
     * 数据组织
     * @param res
     * @return
     */
    private List<SwAuTvmCashAndItvmAmountHierarchyDifferenceDto> getMapList(List<Map<String, Object>> res) {
        List<SwAuTvmCashAndItvmAmountHierarchyDifferenceDto> records = new ArrayList<>();
        for (int i = 0; i < res.size(); i++) {
            Map<String, Object> map = res.get(i);
            String payType = String.valueOf(map.get("payType"));
            if("1".equals(payType)){
                payType = "现金";
            }else {
                payType = "电子";
            }
            SwAuTvmCashAndItvmAmountHierarchyDifferenceDto swAuTvmCashAndItvmAmountHierarchyDifferenceDto = new SwAuTvmCashAndItvmAmountHierarchyDifferenceDto();
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setId((Integer) map.get("id"));

            SwParamLine swParamLine = swParamLineMapper.selectOne(Wrappers.<SwParamLine>lambdaQuery().eq(SwParamLine::getCode, map.get("lineCode")));
            SwParamStation swParamStation = swParamStationMapper.selectOne(Wrappers.<SwParamStation>lambdaQuery()
                    .eq(SwParamStation::getLineCode,map.get("lineCode")).eq(SwParamStation::getCode, map.get("stationCode")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setLineCode(swParamLine.getName());
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setStationCode(swParamStation.getName());
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setTvmCode((String) map.get("tvmOrder"));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setSettleTime(DateFormat.StringTurnLocalDate(map.get("settleTime").toString()));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setPayType(payType);
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setDepositAmount(getFixed((BigDecimal) map.get("depositAmount")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setSaleAmount(getFixed((BigDecimal) map.get("saleAmount")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setErrorRefundAmount(getFixed((BigDecimal) map.get("errorRefundAmount")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyRechargeMoney(getFixed((BigDecimal) map.get("replyRechargeMoney")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplySaleMoney(getFixed((BigDecimal) map.get("replySaleMoney")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyErrorReturnMoney(getFixed((BigDecimal) map.get("replyErrorReturnMoney")));

            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setBeDepositAmount(getFixed((BigDecimal) map.get("beDepositAmount")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setBeSaleAmount(getFixed((BigDecimal) map.get("beSaleAmount")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setBeErrorRefundAmount(getFixed((BigDecimal) map.get("beErrorRefundAmount")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyComparativeRechargeMoney(getFixed((BigDecimal) map.get("replyComparativeRechargeMoney")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyComparativeSaleMoney(getFixed((BigDecimal) map.get("replyComparativeSaleMoney")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setReplyComparativeErrorReturnMoney(getFixed((BigDecimal) map.get("replyComparativeErrorReturnMoney")));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setQfReplyReason(StringUtils.isEmpty(map.get("qfReplyReason").toString()) ? " " : (map.get("qfReplyReason").equals("1") ? "系统原因" : "非系统原因"));
            swAuTvmCashAndItvmAmountHierarchyDifferenceDto.setQfReplyDetail(StringUtils.isEmpty(map.get("qfReplyDetail").toString()) ? " " : map.get("qfReplyDetail").toString());
            records.add(swAuTvmCashAndItvmAmountHierarchyDifferenceDto);
        }
        return records;
    }

    /**
     * TVM票款层级差异协查导入
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "TVM票款层级差异协查导入", notes = "TVM票款层级差异协查导入")
    @SysLog("TVM票款层级差异协查导入")
    @PostMapping({ "/importTVM" })
    public R importTVM(@RequestParam("file") final MultipartFile file) throws Exception {

        final File excelFile = MultipartFileToFile.multipartFileToFile(file);
        List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(2).doReadSync();
        if (CollectionUtil.isNotEmpty(listMap)) {
            List<SwAuTvmCashAmountHierarchyDifference> tvmCashList = new ArrayList<>();
            List<SwAuItvmOnlineAmountHierarchyDifference> itvmOnlineList = new ArrayList<>();
            MultipartFileToFile.delteTempFile(excelFile);
            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 key表示所在的列位置 value表示所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

                if("现金".equals(data.get(5))){
                    SwAuTvmCashAmountHierarchyDifference tvmCash = new SwAuTvmCashAmountHierarchyDifference();
                    tvmCash.setId(Integer.parseInt(data.get(0)));//主键id
                    tvmCash.setReplySaleMoney(getData(data.get(7)));//LC回馈售卖
                    tvmCash.setReplyRechargeMoney(getData(data.get(9)));//LC回馈充值
                    tvmCash.setReplyErrorReturnMoney(getData(data.get(11)));//LC回馈退款
                    tvmCash.setReplyComparativeSaleMoney(getData(data.get(13)));//ACC回馈售卖
                    tvmCash.setReplyComparativeRechargeMoney(getData(data.get(15)));//ACC回馈充值
                    tvmCash.setReplyComparativeErrorReturnMoney(getData(data.get(17)));//ACC回馈退款
                    if("系统原因".equals(data.get(18))){
                        tvmCash.setQfReplyReason("1");//回馈原因
                    }
                    if("非系统原因".equals(data.get(18))){
                        tvmCash.setQfReplyReason("2");//回馈原因
                    }
                    tvmCash.setQfReplyDetail(data.get(19));//回馈描述
                    //tvmCash.setQfReplyStatus("1");//已回馈 改为导入后手动提交
                    tvmCashList.add(tvmCash);
                }else {
                    SwAuItvmOnlineAmountHierarchyDifference itvmOnline = new SwAuItvmOnlineAmountHierarchyDifference();
                    itvmOnline.setId(Integer.parseInt(data.get(0)));//主键id
                    itvmOnline.setReplySaleMoney(getData(data.get(7)));//LC回馈售卖
                    itvmOnline.setReplyRechargeMoney(getData(data.get(9)));//LC回馈充值
                    itvmOnline.setReplyErrorReturnMoney(getData(data.get(11)));//LC回馈退款
                    itvmOnline.setReplyComparativeSaleMoney(getData(data.get(13)));//ACC回馈售卖
                    itvmOnline.setReplyComparativeRechargeMoney(getData(data.get(15)));//ACC回馈充值
                    itvmOnline.setReplyComparativeErrorReturnMoney(getData(data.get(17)));//ACC回馈退款
                    if("系统原因".equals(data.get(18))){
                        itvmOnline.setQfReplyReason("1");//回馈原因
                    }
                    if("非系统原因".equals(data.get(18))){
                        itvmOnline.setQfReplyReason("2");//回馈原因
                    }
                    itvmOnline.setQfReplyDetail(data.get(19));//回馈描述
                    //itvmOnline.setQfReplyStatus("1");//已回馈 改为导入后手动提交
                    itvmOnlineList.add(itvmOnline);
                }

            }
            //  增加根据id批量更新回馈信息方法
            if(CollectionUtils.isNotEmpty(tvmCashList)){
                swAuTvmCashAmountHierarchyDifferenceServices.updateBatchById(tvmCashList);
            }
            if(CollectionUtils.isNotEmpty(itvmOnlineList)){
                swAuItvmOnlineAmountHierarchyDifferenceService.updateBatchById(itvmOnlineList);
            }

        }

        return R.ok();
    }

    /**
     * 金额转换 乘100
     * @param money
     * @return
     */
    private BigDecimal getData(String money){
        try {
            BigDecimal num = new BigDecimal("100");
            BigDecimal itemMoney = new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP);
            itemMoney = itemMoney.multiply(num);
            return itemMoney;

        } catch (Exception e) {
            return new  BigDecimal("0.00");
        }

    }

    /**
     * 金额转换 除100
     * @param money
     * @return
     */
    private BigDecimal getFixed(BigDecimal money){
        if(money!=null){
            BigDecimal num = new BigDecimal("100");
            BigDecimal itemMoney = money.divide(num);
            itemMoney = itemMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
            return itemMoney;
        }else {
            return new  BigDecimal("0.00");
        }


    }

    /**
     * 撤回TVM层级差异 撤回
     * @param
     * @return
     */
    @RequestMapping("/revokeTvmCengJi")
    @ApiOperation(value = "撤回TVM层级差异 撤回", notes = "撤回TVM层级差异 撤回")
    public R revokeTvmCengJi(String ids) {
        List<SwAuTvmCashAmountHierarchyDifference> tvmCashAmountHierarchyDifferences = swAuTvmCashAmountHierarchyDifferenceMapper.selectBatchIds(Arrays.asList(ids.split(",")));
        if(CollectionUtil.isNotEmpty(tvmCashAmountHierarchyDifferences)){
            for(SwAuTvmCashAmountHierarchyDifference tvmCashAmountHierarchyDifference:tvmCashAmountHierarchyDifferences){
                if("1".equals(tvmCashAmountHierarchyDifference.getReplaceStatus())){
                    return R.failed("已经替换的数据不能撤回！");
                }
                SwAuTvmCashAmountHierarchyDifference s=new SwAuTvmCashAmountHierarchyDifference();
                s.setId(tvmCashAmountHierarchyDifference.getId());
                //s.setJdReplyStatus("0");//机电回馈状态改为0，未回馈
                s.setAssistStatus("2");//协查状态改为2，待协查
                swAuTvmCashAmountHierarchyDifferenceMapper.updateById(s);
            }
        }
        return R.ok();
    }
}
